/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author new
 */
public class Assembler {

    public void assemble(String sourceFile) throws FileNotFoundException, IOException{
        String temp = "AssembleTemp";
        FileHandler fh = new FileHandler();
        BufferedReader br = fh.openReadFile(sourceFile);
        BufferedWriter bw = fh.openWriteFile(temp);
        Pattern pattern = Pattern.compile("\\w");
        Matcher matcher;

        NumberHandler nth = new NumberHandler();
        MnemonicHandler mth = new MnemonicHandler();

        String tempStr = br.readLine();

        while(tempStr != null){
            if(tempStr.contains("at")){
                bw.newLine();
                bw.append(tempStr);
                bw.newLine();
                tempStr = br.readLine();
                continue;
            }
            if(tempStr.contains("DB")){
                bw.append(tempStr.substring(tempStr.indexOf("DB") + 3).toUpperCase());
                tempStr = br.readLine();
                continue;
            }
            matcher = pattern.matcher(tempStr);
            if(matcher.find()){
                tempStr = nth.toHexAfterMnemonic(tempStr);
                tempStr = mth.toHex(tempStr);
                bw.append(tempStr.toUpperCase());
            }
            
            tempStr = br.readLine();
        }

        fh.closeReadFile(br);
        fh.closeWriteFile(bw);
        System.gc();
        fh.replaceFile(temp, sourceFile);
    }

}
